package com.xiyou.week02.set;

import java.util.HashSet;

/**
 * 874. 模拟行走机器人
 *
 * @ClassName：RobotSim
 * @Author：西柚
 * @Date：2022/1/8 3:55 下午
 * @Versiion：1.0
 */
public class RobotSim {

    /**
     * 输入：commands = [4,-1,4,-2,4], obstacles = [[2,4]]
     * 输出：65
     * 解释：机器人开始位于 (0, 0)：
     * 1. 向北移动 4 个单位，到达 (0, 4)
     * 2. 右转
     * 3. 向东移动 1 个单位，然后被位于 (2, 4) 的障碍物阻挡，机器人停在 (1, 4)
     * 4. 左转
     * 5. 向北走 4 个单位，到达 (1, 8)
     * 距离原点最远的是 (1, 8) ，距离为 12 + 82 = 65
     *
     * @param commands
     * @param obstacles
     * @return
     */
    public static int robotSim(int[] commands, int[][] obstacles) {
        HashSet<Long> obs = new HashSet<Long>();
        for (int[] obstacle : obstacles) {
            obs.add(calcHash(obstacle));
        }
        int x = 0, y = 0;
        int dir = 0;    // N=0,E=1,S=2,W=3
        // 网格中行走题目，技巧：方向数组
        int[] dx = {0, 1, 0, -1};
        int[] dy = {1, 0, -1, 0};
        int ans = 0;
        int nx, ny;
        for (int command : commands) {
            if (command == -1) {
                dir = (dir + 1) % 4;
            } else if (command == -2) {
                dir = (dir + 3) % 4;
            } else {
                for (int i = 0; i < command; i++) {
                    nx = x + dx[dir];
                    ny = y + dy[dir];
                    // 如果obs.contains(...)，是障碍物
                    if (obs.contains(calcHash(new int[]{nx, ny}))) {
                        break;
                    }
                    x = nx;
                    y = ny;
                    ans = Math.max(ans, x * x + y * y);
                }
            }
        }
        return ans;
    }

    private static Long calcHash(int[] obstacle) {
        return (obstacle[0] + 30000) * 60001L + (obstacle[1] + 30000);
    }

    public static void main(String[] args) {
        int[] commands = {4, -1, 4, -2, 4};
        int[][] obstacles = {{2, 4}};

        System.out.println(robotSim(commands, obstacles));
    }
}
